<template>
    <div class="user_manage">
        <div class="search_bar">
            <div class="search_lt">
                <el-input v-model="keyWord" placeholder="请输入关键词" clearable />
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </div>
            <div class="search_rt">
                <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
        </div>
        <el-table :data="tableData" stripe border :height="height">
            <el-table-column type="index" label="序号" width="55">
                <template #default="scope">
                    {{ ((page - 1) * limit + scope.$index + 1) }}
                </template>
            </el-table-column>
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="realName" label="姓名" />
            <el-table-column prop="orgName" label="部门">
                <template #default="scope">
                    <span>{{ orgs.find(el => scope.row.orgId === el.id)?.name }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" />
            <el-table-column prop="gender" label="性别">
                <template #default="scope">
                    <span v-show="(scope.row.gender === 1)">女</span>
                    <span v-show="(scope.row.gender === 0)">男</span>
                </template>
            </el-table-column>
            <el-table-column prop="post" label="岗位" />
            <el-table-column prop="roleNameList" label="角色">
                <template #default="scope">
                    <span>{{ roleIds.filter(el => scope.row.roleIdList.split(',').includes('' + el.id)).map(el =>
                            el.name).join(",")
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
                <template #default="scope">
                    <el-button type="primary" link @click="handleLook(scope.row)">查看详情</el-button>
                    <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDel(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[20, 100, 300, 500]"
                layout="total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>

    <el-dialog v-model="addEditShow" v-if="addEditShow" :title="(editItem ? '编辑' : '新增') + '用户'" width="480px">
        <add-edit :editItem="editItem" ref="AddEditRef"></add-edit>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addEditShow = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确 定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="lookInfoShow" v-if="lookInfoShow" title="用户详情" width="960px">
        <look-info :lookItem="lookItem"></look-info>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, Ref } from '@vue/reactivity';
import { onMounted, ref } from 'vue'
import { getUser, postUser, putUser, deleteUser } from '@/api/SystemSet/UserManage'
import AddEdit from './AddEdit.vue'
import LookInfo from './LookInfo.vue'
import { ElMessage, ElMessageBox } from "element-plus";

const height = computed(() => window.innerHeight - 220)

const keyWord = ref('')

let page = ref(1)
let limit = ref(20)
let total = ref(0)

let tableData: Ref = ref([])

let addEditShow = ref(false)
let editItem = ref()
const AddEditRef = ref()

let lookInfoShow = ref(false)
let lookItem = ref(null)

onMounted(() => {
    getTableData()
})

const orgs = [
    { id: 1, name: '研发部' },
    { id: 2, name: '销售1部' },
    { id: 3, name: '销售2部' },
]

const roleIds = [
    { name: '管理员', id: 1 },
    { name: '开发人员', id: 2 },
    { name: '销售人员', id: 3 }
]

const getTableData = () => {
    getUser({ page: page.value, limit: limit.value, keyWord: keyWord.value }).then((res: any) => {
        tableData.value = res
        // total.value = res.total
    })
}

const handleSearch = () => {
    page.value = 1
    getTableData()
}

const handleAdd = () => {
    addEditShow.value = true
    editItem.value = null
}

const handleEdit = (row: any) => {
    addEditShow.value = true
    editItem.value = row
}

const handleLook = (row: any) => {
    lookInfoShow.value = true
    lookItem.value = row
}

const handleDel = (row: any) => {
    ElMessageBox.confirm(
        `确定删除用户：${row.realName}（${row.userName}）?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteUser({ id: row.id }).then((res: any) => {
                getTableData()
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            })
        })
}

const handleSubmit = async () => {
    await AddEditRef.value.ruleFormRef.validate((valid: any, fields: any) => {
        if (valid) {
            let form = AddEditRef.value.ruleForm

            form.roleIdList = form.roleIdList.join(',')

            let asyncFun: any = postUser
            if (editItem.value) {
                asyncFun = putUser
            }

            asyncFun(form).then((res: any) => {
                getTableData()
                addEditShow.value = false
                ElMessage({
                    message: '操作成功！',
                    type: "success",
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const handleSizeChange = (val: number) => {
    limit.value = val
    page.value = 1
    getTableData()
}
const handleCurrentChange = (val: number) => {
    page.value = val
    getTableData()
}
</script>

<style lang="less" scoped>
.user_manage {
    padding: 16px;

    .search_bar {
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;

        .el-input {
            width: 240px;
            margin-right: 10px;
        }
    }

    .pagination {
        padding: 10px;
        text-align: center;
        display: flex;
        justify-content: space-around;

        .el-pagination {
            margin: auto;
        }
    }
}
</style>